package com.zl.tby.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyVillageInfoQuery;
import com.zl.tby.dto.TbyVillagePersonQuery;
import com.zl.tby.model.TbyVillageInfo;
import com.zl.tby.model.TbyVillagePerson;
import com.zl.tby.repository.TbyVillagePersonRepo;
import com.zl.tby.service.ITbyVillageInfoService;
import com.zl.tby.service.ITbyVillagePersonService;
import com.zl.tby.vo.TbyVillagePersonForm;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import javax.tools.Tool;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 村庄人口接口实现类
 * @author sunjiaxing
 * @version 1.0
 * @since 2024/8/22 00:23
 */
@Slf4j
@Component
public class TbyVillagePersonServiceImpl implements ITbyVillagePersonService {

    @Db
    private TbyVillagePersonRepo tbyVillagePersonRepo;
    @Db
    private DbContext db;
    @Inject
    private ITbyVillageInfoService tbyVillageInfoService;

    @Override
    @Tran
    public R<TbyVillagePerson> add(TbyVillagePersonForm form) {
        TbyVillagePerson entity = form.createEntity();
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyVillagePersonRepo.insert(entity, true);
        entity.setId(id);
        updateVillage(form);
        return R.ok(entity);
    }

    @Override
    @Tran
    public R<TbyVillagePerson> update(TbyVillagePersonForm form) {
        TbyVillagePerson entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        form.updateEntity(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyVillagePersonRepo.updateById(entity, false);
        updateVillage(form);
        return R.ok(entity);
    }

    private void updateVillage(TbyVillagePersonForm form) {
        if (form.getYear().equals(ToolsUtil.getYear() + "")) {
            // 只有修改今年的才会同步
            this.tbyVillageInfoService.updatePersonById(form.getVillageId(), form.getRegisteredPopulation(), form.getPermanentPopulation(), form.getLabourForce());
        }
    }

    @Override
    public R<Void> delete(Long id) {
        int flag = tbyVillagePersonRepo.deleteById(id);
        return flag > 0 ? R.ok() : R.failed("删除失败");
    }

    @Override
    public TbyVillagePerson get(Long id) {
        return tbyVillagePersonRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyVillagePerson> page(TbyVillagePersonQuery query) {
        IPage<TbyVillagePerson> iPage = tbyVillagePersonRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getVillageId()), "village_id = ?", query.getVillageId())
                    .andIf(StringUtils.isNotEmpty(query.getYear()), " year = ?", query.getYear());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        return new TbyPageResult(iPage, query);
    }

    @Override
    public List<TbyVillagePerson> list(TbyVillagePersonQuery query) {
        return tbyVillagePersonRepo.selectList(mp -> {
            mp.whereTrue()
                    .andIf(ToolsUtil.isNotNull(query.getVillageId()), "village_id = ?", query.getVillageId())
                    .andIf(StringUtils.isNotEmpty(query.getYear()), " year = ?", query.getYear());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
    }

    @Override
    public List<TbyVillagePerson> personCountByYear(String startYear, String endYear, Integer villageId) {
        if (StringUtils.isEmpty(startYear) || StringUtils.isEmpty(endYear)) {
            return new ArrayList<>();
        }
        try {
            DbTableQuery query = db.table("tby_village_person").whereTrue()
                    .andIf(StringUtils.isNotEmpty(startYear), "year >= ?", startYear)
                    .andIf(StringUtils.isNotEmpty(endYear), "year <= ?", endYear)
                    .andIf(villageId != null, "village_id = ?", villageId)
                    .groupBy("year").orderByAsc("year");
            List<TbyVillagePerson> dbList = query.selectList("year, sum(registered_population) registered_population, sum(permanent_population) permanent_population, sum(labour_force) labour_force", TbyVillagePerson.class);
            Map<String, TbyVillagePerson> map = new HashMap<>();
            for (TbyVillagePerson entity : dbList) {
                map.put(entity.getYear(), entity);
            }
            int start = Integer.parseInt(startYear);
            int end = Integer.parseInt(endYear);
            List<TbyVillagePerson> resultList = new ArrayList<>();
            for (int i = start; i <= end; i++) {
                TbyVillagePerson entity = map.get(i + "");
                if (entity == null) {
                    entity = new TbyVillagePerson();
                    entity.setYear(i + "");
                    entity.setLabourForce(-1000L);
                    entity.setRegisteredPopulation(-1000L);
                    entity.setPermanentPopulation(-1000L);
                }
                resultList.add(entity);
            }
            return resultList;
        } catch (Exception ex) {
            log.error("查询村庄人数异常", ex);

        }
        return new ArrayList<>();
    }

    @Override
    public void autoRsyncPersonCount(boolean check) {
        if (check == true) {
            String currentDate = ToolsUtil.dateUtil2String(new Date(), "MM-dd HH");
            if (!currentDate.equals("01-01 00")) {
                return;
            }
        }
        int year = ToolsUtil.getYear();
        List<TbyVillageInfo> villageList = this.tbyVillageInfoService.list(new TbyVillageInfoQuery());
        if (villageList != null) {
            for (TbyVillageInfo village : villageList) {
                TbyVillagePersonQuery query = new TbyVillagePersonQuery();
                query.setYear(year + "");
                query.setVillageId(village.getId());
                List<TbyVillagePerson> personList = this.list(query);
                if (personList == null || personList.size() == 0) {
                    // 今年没有数据，拷贝去年的数据
                    query = new TbyVillagePersonQuery();
                    query.setYear((year - 1) + "");
                    query.setVillageId(village.getId());
                    personList = this.list(query);
                    if (personList != null && personList.size() > 0) {
                        TbyVillagePerson data = personList.get(0);
                        data.setId(null);
                        data.setYear(year + "");
                        this.tbyVillagePersonRepo.insert(data, true);
                    }
                }
            }
        }
    }
}
